package com.ftg.learn.util;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

/**
 * 配置mybatis
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/3/30 上午9:05
 */
@Configuration
@MapperScan("com.ftg.learn.mapper")
public class MybatisConfig {

//    @Bean
//    public SqlSessionFactoryBean initSqlsession(){
//
//        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
//
//        TransactionFactory transactionFactory = new JdbcTransactionFactory();
//
//        PooledDataSource p = new PooledDataSource();
//        p.setUsername("root");
//        p.setPassword("123456");
//        p.setUrl("jdbc:mysql://localhost:10086/database01");
//        p.setDriver("com.mysql.cj.jdbc.Driver");
//
//        Environment localmysql = new Environment("localmysql",transactionFactory,p);
//
//        config.setEnvironment(localmysql);
//
//        config.setLogImpl(StdOutImpl.class);
//
//        XMLMapperBuilder xml = new XMLMapperBuilder(MybatisConfig.class.getResourceAsStream("/com/ftg/learn/mapper/xml/Clazz.xml"),config,"/config/student.xml",config.getSqlFragments());
//        xml.parse();
//
//        config.addMappers("com.ftg.learn.mapper");
//
//        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//        sqlSessionFactoryBean.setConfiguration(config);
//        return sqlSessionFactoryBean;
//    }

    /**
     * sqlsessionfactory
     * @return
     */
    @Bean
    public SqlSessionFactoryBean initSqlsession(){

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(initDatasource());

        Resource r = new ClassPathResource("com/ftg/learn/mapper/xml/Clazz.xml");
        sqlSessionFactoryBean.setMapperLocations(r);
        return sqlSessionFactoryBean;
    }

    /**
     * 数据 源
     * @return
     */
    @Bean
    public DataSource initDatasource(){
        PooledDataSource p = new PooledDataSource();
        p.setUsername("root");
        p.setPassword("123456");
        p.setUrl("jdbc:mysql://localhost:10086/database2212");
        p.setDriver("com.mysql.cj.jdbc.Driver");
        return p;
    }
}
